package com.dimong.loan.sdk.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.inputmethod.InputMethodManager;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    private static final String CHINESE = "[\u0391-\uFFE5]";

    // 判断当前的app是否在后台
    public static boolean isAppBackgroundRunning(Context context) {
        boolean result = false;
        ActivityManager am = (ActivityManager) context
            .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (!tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (!topActivity.getPackageName().equals(context.getPackageName())) {
                result = true;
            }
        }
        return result;
    }

    /**
     * 应用版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersionName(Context context) {
        String versionName = "";
        int versionCode;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versionCode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return "";
            }
        } catch (Exception e) {

        }
        return versionName;
    }

    /**
     * 应用版本
     *
     * @param context
     * @return
     */
    public static int getAppVersionCode(Context context) {
        String versionName = "";
        int versionCode = 0;
        try {
            // ---get the package info---
            PackageManager pm = context.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), 0);
            versionName = pi.versionName;
            versionCode = pi.versionCode;
            if (versionName == null || versionName.length() <= 0) {
                return 0;
            }
        } catch (Exception e) {

        }
        return versionCode;
    }

    /**
     * 获取xml中的参数
     *
     * @param ctx
     * @return
     */
    public static String getManifestMetaData(Context ctx, String key) {
        try {
            ApplicationInfo appInfo = ctx.getPackageManager()
                .getApplicationInfo(ctx.getPackageName(),
                    PackageManager.GET_META_DATA);
            String msg = appInfo.metaData.getString(key);
            return msg;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取xml中的参数
     *
     * @param ctx
     * @return
     */
    public static int getManifestMetaDataInt(Context ctx, String key) {
        try {
            ApplicationInfo appInfo = ctx.getPackageManager()
                .getApplicationInfo(ctx.getPackageName(),
                    PackageManager.GET_META_DATA);
            int msg = appInfo.metaData.getInt(key);
            return msg;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 设置xml中的参数
     *
     * @param ctx
     * @return
     */
    public static void setManifestMetaData(Context ctx, String key, String value) {
        if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) {
            return;
        }
        try {

            ApplicationInfo appInfo = ctx.getPackageManager()
                .getApplicationInfo(ctx.getPackageName(),
                    PackageManager.GET_META_DATA);
            appInfo.metaData.putString(key, value);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取xml中的参数
     *
     * @param ctx
     * @return
     */
    public static boolean getManifestMetaDataB(Context ctx, String key) {
        try {

            ApplicationInfo appInfo = ctx.getPackageManager()
                .getApplicationInfo(ctx.getPackageName(),
                    PackageManager.GET_META_DATA);
            boolean is = appInfo.metaData.getBoolean(key);
            return is;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 根据名字获取id
     */
    public static int getResource(Context ctx, String imageName) {
        int resId = ctx.getResources().getIdentifier(imageName, "drawable", ctx.getPackageName());
        return resId;
    }

    public static int convertStringToColor(String colorStr) {
        int color = 0;
        if (!TextUtils.isEmpty(colorStr)) {
            try {
                color = Color.parseColor(colorStr);
            } catch (Exception e) {

            }
        }
        return color;
    }


    public static void hideSoftInput(final Activity a,
                                     int duration) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                try {
                    InputMethodManager inputManager = (InputMethodManager) a
                        .getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.hideSoftInputFromWindow(a.getCurrentFocus()
                        .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {

                }
            }
        }, duration);
    }

    public static void popSoftInput(final Activity a, int duration) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager imm = (InputMethodManager) a
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, duration);
    }

    public static void hideSoftInput(Activity a) {

        try {
            InputMethodManager inputManager = (InputMethodManager) a
                .getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(a.getCurrentFocus()
                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (Exception e) {

        }
    }

    public static void popSoftInput(Activity a) {
        InputMethodManager imm = (InputMethodManager) a
            .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

    }
//
//    // 设置cookie
//    public static void synCookies(Context context, WebView webView, final String url, List<Cookie> cookies) {
//        if (cookies == null) {
//            return;
//        }
//        List<Cookie> cookieList = new ArrayList<>();
//        cookieList.addAll(cookies);
//
//        CookieSyncManager.createInstance(context);
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.removeAllCookie();
//        CookieSyncManager.getInstance().sync();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            cookieManager.setAcceptThirdPartyCookies(webView, true);
//        } else {
//            cookieManager.setAcceptCookie(true);
//        }
//
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            cookieManager.removeSessionCookies(new ValueCallback<Boolean>() {
//                @Override
//                public void onReceiveValue(Boolean value) {
//                }
//            });
//            cookieManager.removeAllCookies(new ValueCallback<Boolean>() {
//                @Override
//                public void onReceiveValue(Boolean value) {
//                }
//            });
//            for (Cookie cookie : cookieList) {
//                LogHelper.e("COOKIE", "url = " + url + ":cookie=" + cookie.toString());
//                cookieManager.setCookie(url, cookie.toString());
//            }
//            cookieManager.flush();
//        } else {
////            cookieManager.removeSessionCookie();
////            cookieManager.removeAllCookie();
//            for (Cookie cookie : cookieList) {
//                LogHelper.e("COOKIE", "url = " + url + ":cookie=" + cookie.toString());
//                cookieManager.setCookie(url, cookie.toString());
//            }
//            CookieSyncManager.getInstance().sync();
//        }
//        CookieManager.getInstance().acceptCookie();
//    }
//
//    // 清除cookie
//    private void removeCookie(Context context) {
//        CookieSyncManager.createInstance(context);
//        CookieManager cookieManager = CookieManager.getInstance();
//        cookieManager.removeAllCookie();
//        CookieSyncManager.getInstance().sync();
//    }

    /**
     * 获取进程名字
     *
     * @param context
     * @return
     */
    public static String getCurProcessName(Context context) {
        int pid = android.os.Process.myPid();
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfos = mActivityManager.getRunningAppProcesses();
        if (runningAppProcessInfos == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo appProcess : runningAppProcessInfos) {
            if (appProcess.pid == pid) {
                return appProcess.processName;
            }
        }
        return null;
    }

    /* 是否为英文字符 */
    public static boolean isEnglish(char charStr) {
        int mid = charStr;
        if (mid >= 33 && mid <= 126) {
            return true;
        }
        return false;
    }

    /* 是否为中文字符串 */
    public static boolean isChinese(String str) {
        String regEx = "[\\u4e00-\\u9fa5]+";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        if (m.find())
            return true;
        else
            return false;
    }

    public static int textLength(String text) {
        int valueLength = 0;
        int textLength = text.length();
        /* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < textLength; i++) {
            /* 获取一个字符 */
            String temp = text.substring(i, i + 1);
            /* 判断是否为中文字符 */
            if (temp.matches(CHINESE)) {
				/* 中文字符长度为2 */
                valueLength += 2;
            } else {
				/* 其他字符长度为1 */
                valueLength += 1;
            }
        }
        return valueLength;
    }

    public static String formatString(String text, int max, boolean hasDefault) {
        if (textLength(text) <= max) {
            return text;
        }
        int valueLength = 0;
        int textLength = text.length();
        StringBuffer buff = new StringBuffer();
		/* 获取字段值的长度，如果含中文字符，则每个中文字符长度为2，否则为1 */
        for (int i = 0; i < textLength; i++) {
			/* 获取一个字符 */
            String temp = text.substring(i, i + 1);
            			/* 判断是否为中文字符 */
            if (temp.matches(CHINESE)) {
				/* 中文字符长度为2 */
                if (valueLength + 2 <= max) {
                    valueLength += 2;
                    buff.append(temp);
                } else {
                    break;
                }
            } else {
				/* 其他字符长度为1 */
                if (valueLength + 1 <= max) {
                    valueLength += 1;
                    buff.append(temp);
                } else {
                    break;
                }
            }
        }

        if (hasDefault) {
            buff.append("...");
        }
        return buff.toString();
    }
}
